#include <stdio.h>
#include <stdlib.h>

#include <string.h>

#include <strings.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>


#define SERV_PORT 9877
#define MAX_LINE  4096
#define SA  struct sockaddr


void dg_cli(FILE * fp, int sockfd, const SA* pservAddr, socklen_t len)
{
	int n;
	char sendLine[MAX_LINE]={0}, recvLine[MAX_LINE+1]={0};
	while(fgets(sendLine, MAX_LINE, fp)) {
		sendto(sockfd, sendLine, strlen(sendLine), 0, pservAddr, len);
		n = recvfrom(sockfd, recvLine, MAX_LINE,0, NULL, NULL);
		printf("recv n=%d\n", n);
		recvLine[n] = 0;
		fputs(recvLine, stdout);
	}
}

int main(int argc, char**argv)
{
	int sockfd;
	struct sockaddr_in servAddr;
	if (argc != 2) {
		printf("usage: udpcli <ipaddress>\n");
		return 0;
	}
	bzero(&servAddr, sizeof(servAddr));
	servAddr.sin_family = AF_INET;
	servAddr.sin_port = htons(SERV_PORT);
	inet_pton(AF_INET, argv[1], &servAddr.sin_addr);
	sockfd = socket(AF_INET, SOCK_DGRAM, 0);
	dg_cli(stdin, sockfd, (SA*)&servAddr, sizeof(servAddr));
	exit(0);
}
